package com.binaryTree;

public class MaximumBinaryTree0304_645 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return constructTree(nums, 0, nums.length);
    }

    private TreeNode constructTree(int[] nums, int leftIndex, int rightIndex) {
        if(rightIndex - leftIndex < 1) return null;
        if(rightIndex - leftIndex == 1) return new TreeNode(nums[leftIndex]);
        int maxIndex = leftIndex;
        int maxVal = nums[maxIndex];
        for (int i = leftIndex+1; i < rightIndex; i++) {
            if(nums[i] > maxVal){
                maxVal = nums[i];
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(maxVal);
        root.left = constructTree(nums, leftIndex,maxIndex);
        root.right = constructTree(nums,maxIndex+1,rightIndex);
        return root;
    }
}
